#!/usr/bin/python2
# -*- coding: utf-8 -*-
import sys
from PyQt4.QtCore import SIGNAL, Qt, QObject
from PyQt4.QtGui import QMainWindow, QApplication, QLabel, QPushButton, QLineEdit, QSlider, QWidget, QVBoxLayout, QGridLayout, QGroupBox, QRadioButton, QSizePolicy, QFrame, QMenu, QMessageBox, QFileDialog
from curve import Curve
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure

version=0.2

class ReflectorCanvas(FigureCanvas):
    def __init__(self,parent=None,dpi=100):
        fig = Figure(dpi=dpi)
        self.axes = fig.add_subplot(111)

        self.update_figure()

        FigureCanvas.__init__(self, fig)
        self.setParent(parent)
        FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)

    def update_figure(self):
        pass

class ApplicationWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.setWindowTitle("Reflector")

        self.file_menu = QMenu('&File', self)
        self.file_menu.addAction('&Save result', self.dialog_save)
        self.file_menu.addAction('&Quit', self.fileQuit, Qt.CTRL + Qt.Key_Q)
        self.menuBar().addMenu(self.file_menu)
        self.help_menu = QMenu('&Help', self)
        self.menuBar().addSeparator()
        self.menuBar().addMenu(self.help_menu)
        self.help_menu.addAction('&About', self.about)

        self.lb_Q = QLabel(u"Ширина светильника(мм)")

        self.le_Q = QLineEdit()
        self.le_Q.setObjectName("Q")
        self.le_Q.setText("400")
        self.lb_d = QLabel(u"Диаметр лампы(мм)")

        self.gb = QGroupBox('T')
        self.rb1 = QRadioButton('T4', self.gb)
        self.rb2 = QRadioButton('T5', self.gb)
        self.rb3 = QRadioButton('T8', self.gb)
        self.a=[self.rb1,self.rb2,self.rb3]
        self.rb1.setChecked(1)
        self.le_d = QLineEdit()
        self.le_d.setObjectName("d")
        self.le_d.setText("12.7")

        self.lb_n = QLabel(u"Кол-во ламп")

        self.le_n = QLineEdit()
        self.le_n.setObjectName("n")
        self.le_n.setText("4")

        self.lb_h = QLabel(u"Запас высоты светильника(мм)")

        self.le_h = QLineEdit()
        self.le_h.setObjectName("h")
        self.le_h.setText("15")

        self.pb = QPushButton()
        self.pb.setObjectName("Draw")
        self.pb.setText(u"Рисовать") 

        self.main_widget = QWidget(self)

        mainlay = QGridLayout(self.main_widget)

        frame = QFrame(self)
        frame.setFrameShape(QFrame.StyledPanel)
        frame.setFrameShadow(QFrame.Raised)

        layout = QVBoxLayout(frame)
        layout.addWidget(self.lb_Q)
        layout.addWidget(self.le_Q)
        layout.addWidget(self.lb_d)
        layout.addWidget(self.rb1)
        layout.addWidget(self.rb2)
        layout.addWidget(self.rb3)
        layout.addWidget(self.le_d)
        layout.addWidget(self.lb_n)
        layout.addWidget(self.le_n)
        layout.addWidget(self.lb_h)
        layout.addWidget(self.le_h)
        layout.addWidget(self.pb)

        mainlay.addWidget(frame,0,0)

        self.rc = ReflectorCanvas(self.main_widget, dpi=100)
        mainlay.addWidget(self.rc,0,1,2,2)
    
        self.main_widget.setFocus()
        self.setCentralWidget(self.main_widget)
        
        QObject.connect(self.pb, SIGNAL("clicked()"),self.update_figure)
        QObject.connect(self.le_d, SIGNAL("editingFinished()"),self.gb_clear)
        QObject.connect(self.rb1, SIGNAL("clicked()"),self.radio1_clicked)
        QObject.connect(self.rb2, SIGNAL("clicked()"),self.radio2_clicked)
        QObject.connect(self.rb3, SIGNAL("clicked()"),self.radio3_clicked)

    def radio1_clicked(self):
        self.le_d.setText("12.7")
        
    def radio2_clicked(self):
        self.le_d.setText("15.9")
        
    def radio3_clicked(self):
        self.le_d.setText("25.4")

    def gb_clear(self):
        for i in self.a:
            i.setCheckable(False)
            i.setCheckable(True)
        
    def compute_figure(self):
        Q = int(self.le_Q.text())
        d = float(self.le_d.text())
        n = int(self.le_n.text())
        h = int(self.le_h.text())
        self.C = Curve(Q,d,n,h)

    def update_figure(self):
        self.compute_figure()
        self.rc.axes.clear()
        self.C.plot(self.rc.axes)
        self.rc.draw()
        
    def save_result(self):
        file_choices = "PNG (*.png)|*.png"
        path = unicode(QFileDialog.getSaveFileName(self,'Save file', '',file_choices))
        if path:
            self.rc.print_figure(path, dpi=300)

    def dialog_save(self):
        if 'self.C' in locals():
            self.save_result()   

        else:
            self.compute_figure()
            self.C.plot(self.rc.axes)
            self.save_result()

    def about(self):
        QMessageBox.about(self, "About Reflector v{0}\n".format(str(version)), u"""
Программа для проектирования отражателей.
Контакты автора: wavilen@gmail.com, wavilen@jabber.ru.
Лицензия: GPL-3""") 

    def fileQuit(self):
        self.close()

app = QApplication(sys.argv)
aw = ApplicationWindow()
aw.setWindowTitle("Reflector")
aw.show()
app.exec_()
